<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Requests\CashAdd;
use App\Models\Goods;
use App\Models\GoodsCategory;
use App\Models\GoodsCollect;
use App\Models\User;
use Illuminate\Http\Request;


class GoodsController extends Controller
{
    // 商品列表
    public function index(Request $request)
    {
        $result = Goods::whereStatus(1);

        // 分类搜索
        if ($category_id = $request->post('category_id')) {
            $result->where('category_id', $category_id);
        }
        // 关键词搜索
        if ($kw = $request->post('kw')) {
            $result->where(function ($query) use ($kw) {
                $query->where('name', 'like', "%{$kw}%")
                    ->orWhere('desc', 'like', "%{$kw}%");
            });
        }
        $sorts = $request->post('sorts');
        // 价格升序
        if ($sorts == 'price_asc') {
            $result->orderBy('price');
        }
        // 价格降序
        if ($sorts == 'price_desc') {
            $result->orderByDesc('price');
        }
        // 销量降序
        if ($sorts == 'sale_desc') {
            $result->orderByDesc('sale_num');
        }
        // 好评降序
        if ($sorts == 'praise_desc') {
            $result->orderByDesc('praise_num');
        }

        $result =  $result->paginate($this->limit, [
            'id', 'name', 'price',
            'stock_num', 'desc', 'cover',
            'service_am', 'service_pm', 'service_night',
            'service_all', 'status', 'sale_num',
            'score'
        ]);
        return $this->writeJson(0, $result->items());
    }

    // 商品详情
    public function detail(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return $this->writeJson(500, null, '参数错误');
        }

        $goods = Goods::whereStatus(1)
            ->where('id', $id)
            ->first([
                'id', 'name', 'price',
                'stock_num', 'desc', 'cover',
                'service_am', 'service_pm', 'service_night',
                'service_all', 'status', 'sale_num',
                'score'
            ]);
        if (empty($goods)) {
            return $this->writeJson(500, null, '数据不存在');
        }

        $goods->increment('view_num');

        return $this->writeJson(0, $goods);
    }

    // 自己的商品列表
    public function indexUser()
    {
        $result = Goods::whereUserId(auth('wechat')->id())
            ->orderByDesc('id')
            ->paginate($this->limit, [
                'id', 'name', 'price',
                'stock_num', 'desc', 'cover',
                'service_am', 'service_pm', 'service_night',
                'service_all', 'status', 'sale_num',
                'score'
            ]);
        return $this->writeJson(0, $result->items());
    }

    // 收藏/取消收藏商品
    public function collect(Request $request)
    {
        $goods_id = $request->post('goods_id');
        $type = $request->post('type'); // 1：收藏，2：取消收藏
        if (!in_array($type, [1, 2])) {
            return $this->writeJson(500, null, 'type参数错误');
        }
        if (empty($goods_id)) {
            return $this->writeJson(500, null, '请选择商品');
        }

        if ($type == 1) {
            // 收藏
            $result = GoodsCollect::collect(auth('wechat')->id(), $goods_id);
            if ($result === true) {
                return $this->writeJson(0, null, '收藏成功');
            } else {
                return $this->writeJson(500, null, $result ?: '收藏失败');
            }
        } else {
            // 取消收藏
            if (GoodsCollect::unCollect(auth('wechat')->id(), $goods_id)) {
                return $this->writeJson(0, null, '取消收藏成功');
            } else {
                return $this->writeJson(500, null, '取消收藏失败');
            }
        }
    }

    // 新增/编辑商品
    public function add(CashAdd $request)
    {
        try {
            // 检查是否有资格
            $user = User::find(auth('wechat')->id());
            if ($user->is_mechanism != 1) {
                return $this->writeJson(500, null, '没有发布商品的权限');
            }

            if ($id = $request->post('id')) {
                // 编辑
                $model = Goods::whereUserId($user->id)->where('id', $id)->first();
            } else {
                // 新增
                $model = new Goods();
            }
            $model->user_id = $user->id;
            $model->name = $request->post('name');
            $model->price = $request->post('price');
            $model->stock_num = $request->post('stock_num');
            $model->desc = $request->post('desc');
            $model->cover = $request->post('cover');
            $model->service_am = $request->post('service_am') ? 1 : 0;
            $model->service_pm = $request->post('service_pm') ? 1 : 0;
            $model->service_night = $request->post('service_night') ? 1 : 0;
            $model->service_all = $request->post('service_all') ? 1 : 0;
            $model->type = 2; // 用户发布的都是服务性商品
            $model->status = 0; // 每次编辑都要审核
            $model->save();
            return $this->writeJson(0, null, $id ? '修改成功' : '发布成功');
        } catch (\Exception $exception) {
            \Log::error($exception);
        }
        return $this->writeJson(500, null, '操作失败');
    }

    // 删除商品
    public function del(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return $this->writeJson(500, null, '参数错误');
        }

        $model = Goods::whereUserId(auth('wechat')->id())
            ->where('id', $id)
            ->first();
        if (empty($model)) {
            return $this->writeJson(500, null, '商品不存在，或已经删除');
        }

        $model->delete();
        return $this->writeJson(0, null, '删除成功');
    }

    // 分类列表
    public function category()
    {
        $list = GoodsCategory::orderByDesc('sorts')->get();
        foreach ($list as $item) {
            $item->createdAt = $item->created_at->format('Y-m-d H:i');
        }
        return $this->writeJson(0, $list);
    }
}
